import collections
import time, datetime
from django.http import HttpResponse,JsonResponse
from django.shortcuts import render, redirect
from django.db.models import Count
from web import models

def dashboard(request, project_id):
    """概览"""
    # 问题的数据处理,根据状态分组
    # status_dict = {}
    # 定义 有序字典
    status_dict = collections.OrderedDict()
    # 对status选择元组进行循环,默认设置count=0
    for key, text in models.Issues.status_choices:
        status_dict[key] = {"text": text, "count": 0}
    Issues_data = models.Issues.objects.filter(project_id=project_id).values("status").annotate(ct=Count("id"))
    # print(Issues_data)  # <QuerySet [{'status': 1, 'ct': 1}, {'status': 2, 'ct': 1}]>
    for item in Issues_data:
        status_dict[item["status"]]["count"] = item["ct"]
    # 项目的参与者获取
    user_list = models.ProjectUser.objects.filter(project_id=project_id).values("user_id", "user__username")
    # 最近的10个问题,指派不为空的
    top_ten_object = models.Issues.objects.filter(project_id=project_id,assign__isnull=False).order_by("-id")[0:10]
    context = {
        "status_dict": status_dict,
        "user_list": user_list,
        "top_ten_object": top_ten_object,
    }
    return render(request, "dashboard.html", context)


def issues_count(request, project_id):
    """ 获取Highcharts 数据并返回"""
    today = datetime.datetime.now()
    date_dict = collections.OrderedDict()  # 有序字典
    for i in range(0, 30):
        date = today - datetime.timedelta(days=i)
        date_dict[date.strftime("%Y-%m-%d")] = [time.mktime(date.timetuple())*1000, 0]

    """
    初始化字典：数据结构：
    {
        2020-03-31：[12121212, 0],
        2020-03-31：[12121212, 0],
        2020-03-31：[12121212, 0],
    }
    
    """
    # 去数据库查询最近30天的数据
    result = models.Issues.objects.filter(project_id=project_id,
                                          create_datetime__gte=today-datetime.timedelta(days=30)).extra(
       select={"ctime": "strftime('%%Y-%%m-%%d', web_issues.create_datetime)"}).values("ctime").annotate(ct=Count("id"))

    # print(result)  # <QuerySet [{'ctime': '2021-02-04', 'ct': 2}, {'ctime': '2021-02-11', 'ct': 1}]>
    for item in result:
        date_dict[item["ctime"]][1] = item["ct"]
    print(date_dict)
    return JsonResponse({"status": True, "data": list(date_dict.values())})











